﻿using Microsoft.Extensions.Logging;
using SqlSugar;

namespace MES.Core
{
    public class SqlSugarHelper
    {
        //注意：不能写成静态的
        public SqlSugarClient Db;//用来处理事务多表查询和复杂的操作
                                 //public SimpleClient<T> CurrentDb { get { return new SimpleClient<T>(Db); } }//用来操作当前表的数据

        public SqlSugarHelper()
        {
            Db = new SqlSugarClient(AppSetting.connectionConfigs);

            //调式代码 用来打印SQL 
            Db.Aop.OnLogExecuting = (sql, pars) =>
            {

                AppSetting.GetService<ILogger<SqlSugarHelper>>().LogInformation("执行的SQL：" + sql + "\r\n" +
                    Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));

                AppSetting.GetService<ILogger<SqlSugarHelper>>().LogDebug("执行的SQL：" + sql + "\r\n" +
              Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));


                AppSetting.GetService<ILogger<SqlSugarHelper>>().LogError("执行的SQL：" + sql + "\r\n" +
              Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));

                AppSetting.GetService<ILogger<SqlSugarHelper>>().LogTrace("执行的SQL：" + sql + "\r\n" +
              Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));

                AppSetting.GetService<ILogger<SqlSugarHelper>>().LogWarning("执行的SQL：" + sql + "\r\n" +
       Db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
            };

        }


        /// <summary>
        /// 切换数据库
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="dbType"></param>
        /// <returns></returns>

        public void ChangeDB(string connectionString, DbType dbType)
        {
            Db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = connectionString,//数据库链接字符串
                DbType = dbType,//指定数据库类型
                IsAutoCloseConnection = true,//链接使用完后是否自动释放
                InitKeyType = InitKeyType.Attribute//从实体特性中读取主键自增列信息

            });
        }
    }
}